import { App } from "vue"

/**
 * @description 安装自定义指令
 * @param app 实例
 */
export function useDirective(app: App<Element>) {
  // 防抖
  app.directive('debounce', {
    // 在元素的 attribute 或事件监听器被应用之前调用
    created(el, binding) {
      let timer: number | null = null
      // 默认延迟时间
      let defaultDelay: number = 300
      // 默认绑定值为执行函数
      let defaultCallback = binding.value
      // 自定义延迟时间,请使用对象形式传入固定参数callback, delay
      if (typeof binding.value === 'object') {
        const {callback, delay} = binding.value || {}
        defaultDelay = delay ?? defaultDelay
        defaultCallback = callback
      }
      
      el.addEventListener(
        'click',
        (event: any) => {
          event && event.stopImmediatePropagation()
          if (!timer) {
            timer = setTimeout(() => {
              defaultCallback()
            }, defaultDelay)
          } else {
            clearTimeout(timer)
            timer = setTimeout(() => {
              defaultCallback()
            }, defaultDelay)
          }
        },
        true
      )
    }
  })


  // 节流
  app.directive('throttle', {
    created(el, binding) {
      let timer: number | null = null
      // 默认延迟时间
      let defaultDelay: number = 1000
      // 默认绑定值为执行函数
      let defaultCallback = binding.value
      // 自定义延迟时间,请使用对象形式传入固定参数callback, delay
      if (typeof binding.value === 'object') {
        const {callback, delay} = binding.value || {}
        defaultDelay = delay ?? defaultDelay
        defaultCallback = callback
      }
      
      el.addEventListener(
        'click',
        (event: any) => {
          if (!timer) {
            timer = setTimeout(() => {
              defaultCallback()
              timer = null
            }, defaultDelay)
          } else {
            event && event.stopImmediatePropagation()
          }
        },
        true
      )
    }
  })
}
